/**
 * 用户认证路由
 * 处理登录、注册和认证相关的API端点
 */

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const User = require('../models/user');
const { protect } = require('../middleware/auth');
const { ErrorResponse } = require('../middleware/error');

/**
 * @desc    注册新用户
 * @route   POST /api/v1/auth/register
 * @access  公开
 */
router.post('/register', async (req, res, next) => {
    try {
        const { username, email, password } = req.body;
        
        // 检查必填字段
        if (!username || !email || !password) {
            return next(new ErrorResponse('请提供用户名、邮箱和密码', 400));
        }
        
        // 验证邮箱是否已存在
        const emailExists = await User.findOne({ email });
        if (emailExists) {
            return next(new ErrorResponse('该邮箱已被注册', 400));
        }
        
        // 验证用户名是否已存在
        const usernameExists = await User.findOne({ username });
        if (usernameExists) {
            return next(new ErrorResponse('该用户名已被使用', 400));
        }
        
        // 创建用户
        const user = await User.create({
            username,
            email,
            password
        });
        
        // 创建响应
        res.status(201).json({
            success: true,
            message: '注册成功',
            user: {
                id: user._id,
                username: user.username,
                email: user.email,
                avatar: user.avatar
            }
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    用户登录
 * @route   POST /api/v1/auth/login
 * @access  公开
 */
router.post('/login', async (req, res, next) => {
    try {
        const { username, password } = req.body;
        
        // 检查必填字段
        if (!username || !password) {
            return next(new ErrorResponse('请提供用户名和密码', 400));
        }
        
        // 查找用户并包含密码字段
        const user = await User.findOne({ username }).select('+password');
        
        // 如果用户不存在
        if (!user) {
            return next(new ErrorResponse('用户名或密码错误', 401));
        }
        
        // 验证密码
        const isMatch = await user.matchPassword(password);
        if (!isMatch) {
            return next(new ErrorResponse('用户名或密码错误', 401));
        }
        
        // 生成JWT令牌
        const token = user.generateAuthToken();
        
        // 移除密码字段
        const userResponse = user.toJSON();
        
        // 创建响应
        res.status(200).json({
            success: true,
            token,
            user: userResponse
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    获取当前登录用户信息
 * @route   GET /api/v1/auth/me
 * @access  私有
 */
router.get('/me', protect, async (req, res, next) => {
    try {
        // 获取用户信息并填充喜欢的游戏
        const user = await User.findById(req.user._id).populate({
            path: 'favoriteGames',
            select: 'title thumbnail category rating'
        });
        
        res.status(200).json({
            success: true,
            user
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    修改密码
 * @route   PUT /api/v1/auth/password
 * @access  私有
 */
router.put('/password', protect, async (req, res, next) => {
    try {
        const { currentPassword, newPassword } = req.body;
        
        // 检查必填字段
        if (!currentPassword || !newPassword) {
            return next(new ErrorResponse('请提供当前密码和新密码', 400));
        }
        
        // 查找用户并包含密码字段
        const user = await User.findById(req.user._id).select('+password');
        
        // 验证当前密码
        const isMatch = await user.matchPassword(currentPassword);
        if (!isMatch) {
            return next(new ErrorResponse('当前密码错误', 401));
        }
        
        // 更新密码
        user.password = newPassword;
        await user.save();
        
        res.status(200).json({
            success: true,
            message: '密码修改成功'
        });
    } catch (error) {
        next(error);
    }
});

/**
 * @desc    检查令牌有效性
 * @route   GET /api/v1/auth/verify
 * @access  私有
 */
router.get('/verify', protect, (req, res) => {
    res.status(200).json({
        success: true,
        message: '令牌有效',
        user: req.user
    });
});

module.exports = router; 